package j20251013;

import java.io.*;
import java.util.Scanner;


public class Demo3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要搜索的路径：");
        String path=sc.next();
        File f=new File(path);
        if(!f.isDirectory()){
            System.out.println("输入的不是路径！");
            return;
        }
        System.out.println("请输入要搜索的关键字：");
        String keyWords=sc.next();

        scafDir(f,keyWords);

    }

    private static void scafDir(File f, String keyWords) {
        File[] files = f.listFiles();
        if(files!=null){
            return;
        }
        for (File file : files) {
            if(file.isFile()){
                dealFile(file,keyWords);
            }else {
                scafDir(file,keyWords);
            }
        }
    }
    private static void dealFile(File file, String keyWords) {
        if(file.getName().contains(keyWords)){
            System.out.println("找到目标文件了"+file.getAbsoluteFile());
        }
        StringBuilder ret=new StringBuilder();
        try (InputStream inputStream = new FileInputStream(file)) {
            while (true) {
                byte[] buf = new byte[1024];
                int len = inputStream.read(buf);
                if (len == -1) {
                    break;
                }
                ret.append(new String(buf,0,len));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(ret.toString().contains(keyWords)){
            System.out.println("发现内容包含关键字目标文件"+file.getAbsoluteFile());
        }
    }
}
